package com.kylin.weixin.utils;

import com.kylin.common.exception.BaseException;

import com.kylin.utils.FileUtils;
import com.kylin.weixin.common.xml.bean.WeChatXmlMessage;
import com.kylin.weixin.config.ThirdPartyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Program Name: dajia-wxapplet
 * <p>
 * Description:   微信第三方管理工具类
 * <p>
 * Created by tongzhq on 2020/6/2 0002 15:09:18
 *
 * @author tongzhq
 * @version 1.0
 */
public class WeChat3rdManageUtil {
    private final static Logger LOGGER = LoggerFactory.getLogger(WeChat3rdManageUtil.class);

    private static final ThirdPartyConfig thirdPartyConfig = new ThirdPartyConfig();

    /**
     * 解密ComponentVerifyTicket
     * @param msg_signature
     * @param timestamp
     * @param nonce
     * @param appID
     * @param encodingAesKey
     * @param token
     * @return
     */
    /**
     * 解析授权事件消息
     * @param request HttpServletRequest
     * @return WeChatXmlMessage
     */
    public static WeChatXmlMessage decodeMessage(HttpServletRequest request) {

        String wx3rdAppId = thirdPartyConfig.getWx3rdAppId();
        String wx3rdEncodingAesKey = thirdPartyConfig.getWx3rdEncodingAesKey();
        String wx3rdToken = thirdPartyConfig.getWx3rdToken();

        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String msgSignature = request.getParameter("msg_signature");
        String encStr;
        try {
            encStr = FileUtils.inputStream2String(request);
            LOGGER.info("解密前:" + encStr);

            WeChatXmlMessage inMessage = WeChatXmlMessage.fromEncryptedXml(request.getInputStream(), wx3rdToken, wx3rdEncodingAesKey,
                    wx3rdAppId, timestamp, nonce, msgSignature);
            if (null == inMessage) {
                throw new BaseException("解析授权事件消息为空");
            }
            return inMessage;
        } catch (IOException e) {
            LOGGER.error("异常：" + e);

            throw new BaseException("Exception:" + e);
        }
    }


}
